<script>
var cy = window.cy = cytoscape({
  container: document.getElementById('cy'),
  minZoom: 0.5,
  maxZoom: 8,
  autounselectify: false,
  selectionType: 'single',
  layout: {
    name: 'dagre'
  },

  style: [
    {
      selector: 'node',
      style: {
        'content': 'data(description)',
        'text-margin-x': 2,
        'text-opacity': 0.5,
        'text-valign': 'center',
        'text-halign': 'right',
        'background-color': 'data(color)',
      }
    },
    {
      selector: 'edge',
      style: {
        'curve-style': 'bezier',
        'width': 4,
        'target-arrow-shape': 'triangle',
        'line-color': '#808080',
        'target-arrow-color': '#808080'
      }
    },
    {
      selector: ':selected',
      style: {
        'background-color': '#C39EC1',
      }
    }
  ],


  elements: {
    nodes: [
    {% for ele in files  %}
    { data: { id: '{{ele.id}}' ,
              href: '{{ele.file_url}}',
              description: '{{ele.description}}',
              timestamp : '{{ele.timestamp}}',
              number_scripts : {{ele.number_scripts}},
              number_sprites : {{ele.number_sprites}},
              ancestors : {{ele.ancestors}},
              color: '{{ ele.color }}'
             }
     },
    {% endfor %}
    ],
    edges: [
    {% for ele in files  %}
        {% for anc in ele.ancestors  %}
        { data: { source: '{{anc}}', target: '{{ele.id}}' } },
        {% endfor %}
    {% endfor %}
    ]
  },
});


// Doubleclick
var tappedBefore = false;
var tappedTimeout;
cy.on('tap', 'node', function(event) {
  var tappedNow = event.cyTarget;
  if (tappedTimeout && tappedBefore) {
    clearTimeout(tappedTimeout);
  }
  if(tappedBefore === tappedNow) {
    this.trigger('dblclick', event.target);
    tappedBefore = null;
  } else {
    tappedTimeout = setTimeout(function(){ tappedBefore = null; }, 300);
    tappedBefore = tappedNow;
  }
});


// Open in Snap on longtap or doubleclick in new tab
cy.on('taphold dblclick', 'node', function(evt){
        if (this.data('href')){
        //ADJUST FOR CERTAIN SERVERSETTINGS
            var url = 'https://snap.berkeley.edu/snapsource/snap.html#open:' + window.location.origin + this.data('href');
            try { // your browser may block popups
                window.open(url,'_blank');
            } catch(e){ // fall back on url change
                window.location.href = url;
            }
        }
    }
);


// Show tooltip on hover
cy.on('click', 'node', function(evt){
  node = evt.target;

  //calculate difference to parent node
  var diff_sprites = 0;
  var diff_scripts = 0;
  // arrow_drop_up und arrow_drop_down als materialize icons
  if (node.data('ancestors').length === 1){
    var parent = cy.$("[id='" + node.data('ancestors')[0] +"']")
    diff_sprites = this.data('number_sprites') - parent.data('number_sprites')
    diff_scripts = this.data('number_scripts') - parent.data('number_scripts')
  }

  diff_sprites_string = (diff_sprites === 0) ? '-' :
        ( diff_sprites > 0 ? '<div style="color:green"> <i class="trend-indicator material-icons">arrow_drop_up</i>'   + diff_sprites + '</div>'
                           : '<div style="color:red">   <i class="trend-indicator material-icons">arrow_drop_down</i>' + diff_sprites*(-1)  + '</div>'
        )
  diff_scripts_string = (diff_scripts === 0) ? '-' :
        ( diff_scripts > 0 ? '<div style="color:green"> <i class="trend-indicator material-icons">arrow_drop_up</i>'+ diff_scripts + '</div>'
                           : '<div style="color:red">   <i class="trend-indicator   material-icons">arrow_drop_down</i>' + diff_scripts*(-1) + '</div>'
        )


  tooltip = '<table>' +
    '<tbody>' +
        '<tr>' +
          '<td>sprites</td>' +
          '<td>' + node.data('number_sprites') + '</td>' +
          '<td>' + diff_sprites_string + '</td>' +
        '</tr>' +
        '<tr>' +
          '<td>scripts</td>' +
          '<td>' + node.data('number_scripts') + '</td>' +
          '<td>' + diff_scripts_string + '</td>' +
        '</tr>' +
        '<tr>' +
          '<td>' + 'smerged ' + format(node.data('timestamp')) + '</td>' +
        '</tr>' +
    '</tbody>' +
  '</table>'

  node.qtip({
      content: tooltip,
      position: {
        my: 'top center',
        at: 'bottom center'
      },
      style: {
        classes: 'qtip-bootstrap',
        tip: {
          width: 16,
          height: 8
        }
      }
  });

});


var toggleMerge = function(){

    if (cy.selectionType() == 'single'){
        cy._private. selectionType = 'additive';
        $("#merge").toggleClass('red green');
        $("#merge>i").text('done');
        $("#cancel-merge").toggleClass('hide');
    }
    else {
        cy._private. selectionType = 'single';
        $("#merge").toggleClass('green red');
        $("#merge>i").text('call_merge');
        $("#cancel-merge").toggleClass('hide');
        cy.$(':selected').unselect();
    }

}


$('#merge').mousedown(function (evt) {

    if (cy.selectionType() == 'single'){
        toggleMerge();
    }
    else {
        var selectedElements = cy.$(':selected');

        if (selectedElements.length > 0){
            console.log(selectedElements);

            var merge_url = 'merge/{{proj_id}}';
            var first = true;
            selectedElements.forEach(function(ele){
                if (first){
                    merge_url += '?';
                    first = false;
                }
                else {
                    merge_url += '&';
                }
                merge_url += 'file='+ele.data('id');
            });

            var merged_node;
            $.ajax({
                url: merge_url,
                cache: false,
                success: function(new_node) {

                },
                error: function(){
                    console.log('merge did not work');
                }
            });
        }

        toggleMerge();
    }
});

$('#cancel-merge').mousedown(toggleMerge);

</script>
